package com.sqx.modules.health.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.modules.health.common.Constants;
import com.sqx.modules.health.common.Result;
import com.sqx.modules.health.entity.*;
import com.sqx.modules.health.service.*;
import com.sqx.modules.sys.entity.SysUserEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author gxy
 * @since 2022-07-14
 */
@Slf4j
@Api(value = "", tags = "", description = "")
@RestController
@RequestMapping("/health/record")
public class RecordController {
    @Autowired
    private IRecordService recordService;
    @Autowired
    private INcgDeviceWatchService watchService;
    @Autowired
    private IReceiveService receiveService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IRecordsetService recordsetService;

    // 新增或更新
    @PostMapping("/save")
    @ApiOperation(value = "新增或更新", notes = "新增或更新")
    public Result save(@RequestBody Record record) {
        return Result.success(recordService.saveOrUpdate(record));
    }

    @PostMapping("/preserve")
    @ApiOperation(value = "新增或更新", notes = "新增或更新")
    public Result preserve(@RequestBody JSONObject jsonObject) {

        NcgDeviceWatch device = watchService.getDeviceByDevNo(jsonObject.get("imei"));
        if (ObjectUtil.isNotEmpty(device)) {
            if (ObjectUtil.equals(device.getStatus(), 2)) {
                return Result.error(Constants.CODE_500, "测量失败,设备使用中,请联系管理员");
            }
        }
        try {
            //修改设备表状态
            watchService.editBinding(jsonObject.get("uid"), jsonObject.get("doctorid"), jsonObject.get("imei"));

            saveRecords(jsonObject);

            if (jsonObject.getLong("type") == 3) {
                return Result.success(recordService.sendPat(jsonObject));
            }else {
                //生成测量数据记录
                Record record = new Record();
                record.setUid(jsonObject.getLong("uid"));
                record.setDoctorid(jsonObject.getLong("doctorid"));
                record.setImei(jsonObject.getString("imei"));
                record.setType(jsonObject.getInteger("type"));
                record.setRecordtime(DateUtil.now());
                record.setFlag(0);
                return Result.success(recordService.saveOrUpdate(record));

            }

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(Constants.CODE_500,"测量失败,请联系管理员");
        }
    }

    private void saveRecords(JSONObject jsonObject) {
        //生成测量次数记录
        QueryWrapper<NcgDeviceWatch> wrapper = new QueryWrapper<NcgDeviceWatch>()
                .eq(ObjectUtil.isNotEmpty(jsonObject.getString("imei")), "imei", jsonObject.getString("imei"));
        NcgDeviceWatch watch = watchService.getOne(wrapper);
        Recordset recordset = new Recordset();
        recordset.setImei(jsonObject.getString("imei"));
        recordset.setUid(jsonObject.getLong("uid"));
        recordset.setDocid(jsonObject.getLong("doctorid"));
        recordset.setStatus(0);
//        recordset.setDevicename(watch.getDevicename());
        recordset.setStartdate(LocalDateTime.now());
        recordset.setDevicetype(Integer.valueOf(watch.getType()));
        recordsetService.saveOrUpdate(recordset);

    }

    // 根据ID删除
    @DeleteMapping("/del/{id}")
    @ApiOperation(value = "根据ID删除", notes = "根据ID删除")
    public Result delete(@PathVariable Integer id) {
        return Result.success(recordService.removeById(id));
    }

    // 根据IDS删除
    @PostMapping("/del/batch")
    @ApiOperation(value = "根据IDS删除", notes = "根据IDS删除")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(recordService.removeByIds(ids));
    }

    // 查询全部
    @GetMapping("/findAll")
    @ApiOperation(value = "查询全部", notes = "查询全部")
    public Result findAll() {
        return Result.success(recordService.list());
    }

    // 根据ID查询一条记录
    @GetMapping("/findOne")
    @ApiOperation(value = "根据ID查询一条记录", notes = "根据ID查询一条记录")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(recordService.getById(id));
    }

    // 分页查询
    @GetMapping("/findPage")
    @ApiOperation(value = "分页查询", notes = "分页查询")
    public Result findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        return Result.success(recordService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    @ApiOperation(value = "获取检测结果", notes = "获取检测结果")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uid", value = "患者id", paramType = "Long"),
            @ApiImplicitParam(name = "type", value = "数据类型 2 血压 1 血糖", paramType = "Integer"),
            @ApiImplicitParam(name = "starttime", value = "开始时间", paramType = "String"),
            @ApiImplicitParam(name = "endtime", value = "结束时间", paramType = "String")
    })
    @GetMapping("getResult")
    public Result getResult(@RequestParam(required = false, defaultValue = "") Long uid,
                            @RequestParam(required = false, defaultValue = "") Integer type,
                            @RequestParam(required = false, defaultValue = "") String startTime,
                            @RequestParam(required = false, defaultValue = "") String endTime) {

        QueryWrapper<Record> queryWrapper = new QueryWrapper<Record>().eq(ObjectUtil.isNotEmpty(uid), "uid", uid)
                .eq(ObjectUtil.isNotEmpty(type), "type", type)
                .between(ObjectUtil.isNotEmpty(startTime) && ObjectUtil.isNotEmpty(endTime), "recordtime", startTime, endTime)
                .orderByDesc("recordtime");

//        Record lastTest = recordService.getLastTest(uid);
//        if (ObjectUtil.isEmpty(lastTest)) {
            return Result.success(EncapsulateResult(queryWrapper));
//        }
//        if (ObjectUtil.equals(lastTest.getFlag(), 1)) {
//            return Result.success(EncapsulateResult(queryWrapper));
//        }
//
//        QueryWrapper<NcgDeviceWatch> wrapper = new QueryWrapper<NcgDeviceWatch>().eq(ObjectUtil.isNotEmpty(lastTest.getImei()), "imei", lastTest.getImei());
//        NcgDeviceWatch device = watchService.getOne(wrapper);
//        if (ObjectUtil.equals(device.getType(), "3")) {
//            return Result.success(EncapsulateResult(queryWrapper));
//        } else if (ObjectUtil.equals(device.getType(), "2") && ObjectUtil.equals(lastTest.getFlag(), 0)) {
////            List<Saihong> collect = getRemoteData(lastTest);
////            if (CollectionUtils.isNotEmpty(collect)) {
////                lastTest.setSys(collect.get(0).getShrink());
////                lastTest.setDia(collect.get(0).getDiastole());app
////                lastTest.setPul(collect.get(0).getRate());
////                lastTest.setFlag(1);
////                recordService.saveOrUpdate(lastTest);
////            }
//            return Result.success(EncapsulateResult(queryWrapper));
//        } else if (ObjectUtil.equals(lastTest.getType(), "4")) {
//            return Result.success(EncapsulateResult(queryWrapper));
//        } else {
//            return Result.error(Constants.CODE_500, "error");
//
//        }
    }

    /**
     * 封装返回结果
     *
     * @param queryWrapper
     * @return
     */
    private List<Record> EncapsulateResult(QueryWrapper<Record> queryWrapper) {
        List<Record> list = recordService.list(queryWrapper);
        list.forEach(item -> {
            if (ObjectUtil.isNotEmpty(item.getDoctorid())) {
                SysUserEntity user = userService.getRedisByUid(item.getDoctorid());
                if (!ObjectUtil.isNotEmpty(user)) {
                    item.setDoctorname(ObjectUtil.isNotEmpty(user.getNickName()) ? user.getNickName() : user.getUsername());
                }
            }
        });
//        list = list.stream().filter(item -> item.getFlag() != 0).collect(Collectors.toList());
        return list;
    }

//    /**
//     * 获取远程数据
//     *
//     * @param record
//     * @return
//     */
//    private List<Saihong> getRemoteData(Record record) {
//        List<Saihong> collect = new ArrayList<>();
//        try {
//            String starttime = ObjectUtil.isEmpty(record.getRecordtime()) ? DateUtil.beginOfDay(new Date()).toString() : record.getRecordtime();
//            String endtime = DateUtil.date().toString();
//            Map<String, Object> params = new HashMap<>();
//            params.put("deviceMac", record.getImei());
//            params.put("starttime", starttime);
//            params.put("endtime", endtime);
//            String param = JSON.toJSONString(params);
//            String result = HttpUtils.sendPost("http://taiyibp.tjtzkt.com/getBpDatas.aspx", param);
//            JSONObject jsonObject1 = JSONObject.parseObject(result);
//            List<Object> data = (List<Object>) jsonObject1.get("data");
//            List<Saihong> saihongs = new ArrayList<>();
//            if (data != null) {
//                for (int i = 0; i < data.size(); i++) {
//                    Saihong saihong = new Saihong();
//                    BeanUtil.copyProperties(data.get(i), saihong);
//                    saihongs.add(saihong);
//                }
//                collect = saihongs.stream().filter(saihong -> ObjectUtil.equals(saihong.getIsValidName(), "有效数据")).collect(Collectors.toList());
//            }
//            List<Surveyrecord> surveyrecords = MyBeanUtil.collectionCopy(collect, Surveyrecord.class);
//            System.out.println(surveyrecords);
//            return collect;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return collect;
//        }
//    }

//    @ApiOperation(value = "结束检测", notes = "结束检测")
//    @GetMapping("/endDetect")
//    public Result endDetect(@RequestParam long uid) {
//        try {
//            Record lastTest = recordService.getLastTest(uid);
//
//            QueryWrapper<NcgDeviceWatch> wrapper = new QueryWrapper<NcgDeviceWatch>().eq(ObjectUtil.isNotEmpty(lastTest.getImei()), "imei", lastTest.getImei());
//
//            NcgDeviceWatch device = watchService.getOne(wrapper);
//
//            if (ObjectUtil.equals(device.getType(), 3)) {
//                return Result.error(Constants.CODE_500, "该功能用于动态血压!");
//            }
//
//            if (ObjectUtil.equals(lastTest.getFlag(), 1)) {
//                return Result.success("success");
//            }
//
//            List<Saihong> collect = getRemoteData(lastTest).stream().sorted(Comparator.comparing(Saihong::getSampleDate)).collect(Collectors.toList());
//
//            Record record = new Record();
//            BeanUtil.copyProperties(lastTest, record);
//            if (CollectionUtils.isNotEmpty(collect)) {
//                for (int i = 0; i < collect.size(); i++) {
//                    if (i == 0) {
//                        lastTest.setSys(collect.get(i).getShrink());
//                        lastTest.setDia(collect.get(i).getDiastole());
//                        lastTest.setPul(collect.get(i).getRate());
//                        lastTest.setFlag(1);
//                        recordService.saveOrUpdate(lastTest);
//                        continue;
//                    }
//                    record.setId(null);
//                    record.setRecordtime(collect.get(i).getSampleDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
//                    record.setSys(collect.get(i).getShrink());
//                    record.setDia(collect.get(i).getDiastole());
//                    record.setPul(collect.get(i).getRate());
//                    record.setFlag(1);
//                    recordService.saveOrUpdate(record);
//                }
//            }
//            return Result.success("检测已停止,数据已同步");
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//    }

    @PostMapping("/uploadReport")
    public Result uploadReport(@RequestBody Map params) {

        LambdaUpdateWrapper<Record> lambdaUpdateWrapper = new LambdaUpdateWrapper<Record>()
                .set(Record::getFile, params.get("file"))
                .set(Record::getFlag, 1)
                .eq(Record::getId, params.get("id"));
        boolean update = recordService.update(lambdaUpdateWrapper);
        String imei = (String) params.get("imei");

        Recordset recordset = recordsetService.getLast(imei);
        recordset.setStatus(1);
        recordset.setEnddate(LocalDateTime.now());
        boolean saveOrUpdate = recordsetService.saveOrUpdate(recordset);

        LambdaUpdateWrapper<NcgDeviceWatch> wrapper = new LambdaUpdateWrapper<NcgDeviceWatch>()
                .set(NcgDeviceWatch::getDoctorid, null)
                .set(NcgDeviceWatch::getUid, null)
                .set(NcgDeviceWatch::getStatus, 3)
                .eq(ObjectUtil.isNotEmpty(imei), NcgDeviceWatch::getImei, imei);
        boolean device = watchService.update(wrapper);

        if (update && saveOrUpdate) {

            return Result.success("文件上传成功");

        } else {

            return Result.error(Constants.CODE_500, "未知原因错误");

        }
    }
}

